package com.wjw.utils;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @desc 基于 Apache的commons-httpclient
 * @author wjw
 * @date 2016年12月16日上午11:49:02
 */
public class HttpUtil {
	
	public static String GBK = "GBK";
	
	public static String UTF8 = "UTF-8";
	
	public static HttpClient client = new HttpClient();
	
	/** log */
	public static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
	
	/**
	 * 设置连接属性
	 * @param maxConnectionPerHost 毫秒
	 * @return
	 */
	public static void setConnectionsParams(int socketTimeOut, int connectionTimeOut, int maxTotalConnections, int maxConnectionPerHost){
		MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
		connectionManager.getParams().setSoTimeout(socketTimeOut);
		connectionManager.getParams().setConnectionTimeout(connectionTimeOut);
		connectionManager.getParams().setMaxTotalConnections(maxTotalConnections);
		connectionManager.getParams().setDefaultMaxConnectionsPerHost(maxConnectionPerHost);
	}
	
	/**
	 * http post 请求
	 * @param url
	 * @return
	 */
	public static String post(String url){
		return post(url, null);
	}
	
	/**
	 * http post 请求
	 * @param url
	 * @param params
	 * @return
	 */
	public static String post(String url, Map<String,String> params){
		return post(url, params,HttpUtil.UTF8);
	}
	
	/**
	 * http post 请求
	 * @param url
	 * @param params
	 * @return
	 */
	public static String post(String url, Map<String,String> params,String enc){
		return post(url, params ,null , enc);
	}
	
	/**
	 * http post 请求
	 * @param url
	 * @param params 请求参数
	 * @param header 请求头属性
	 * @return
	 */
	public static String post(String url, Map<String,String> params ,Map<String, String> header){
		return post(url, params, header, null);
	}
	
	/**
	 * http post 请求
	 * @param url
	 * @param params 请求参数
	 * @param header 头请求
	 * @param enc 编码
	 * @return
	 */
	public static String post(String url, Map<String,String> params, Map<String, String> header, String enc){
		PostMethod method = new PostMethod(url);
		if(null != params){
			Set<String> keySet = params.keySet();
			for(String key : keySet){
				method.addParameter(key, params.get(key));
			}
		}
		return excuteHttp(method, header, enc);
	}
	
	/**
	 * http get 请求
	 * @param url
	 * @return
	 */
	public static String get(String url){
		return get(url, null);
	}
	
	/**
	 * http get 请求
	 * @param url
	 * @param params
	 * @return
	 */
	public static String get(String url, Map<String,String> params){
		return get(url, params, HttpUtil.UTF8);
	}
	
	/**
	 * http get 请求
	 * @param url
	 * @param params
	 * @param enc
	 * @return
	 */
	public static String get(String url, Map<String,String> params, String enc){
		return get(url, params, null, enc);
	}
	
	/**
	 * http get 请求
	 * @param url
	 * @param params
	 * @param header
	 * @return
	 */
	public static String get(String url, Map<String,String> params, Map<String,String> header){
		return get(url, params, header, HttpUtil.UTF8);
	}
	
	/**
	 * http get 请求
	 * @param url
	 * @param params
	 * @param header
	 * @param enc
	 * @return
	 */
	public static String get(String url, Map<String,String> params, Map<String,String> header ,String enc){
		GetMethod method = new GetMethod(getUrl(url, params));
		return excuteHttp(method, header, enc);
	}

	/**
	 * 构建 HttpMethod 进行请求
	 * @param method
	 * @param enc
	 * @return
	 */
	private static String excuteHttp(HttpMethod method, Map<String, String> header, String enc) {
		String response = null;
		try {
			if(null != enc){
				method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + enc);  
			}
			if(null != header){
				Set<String> keySet = header.keySet();
				for(String key : keySet){
					method.setRequestHeader(key, header.get(key));
				}
			}
			response = excuteMethod(response, method);
		} catch (HttpException e) {
			logger.error("发生HttpException,请求内容不正确或证书错误", e);
		} catch (IOException e) {
			logger.error("网络异常", e);
			response="网络异常";
		}finally{
			//释放连接的HTTP方法。
			if(null != method){
				method.releaseConnection();
			}
		}
		return response;
	}

	/**
	 * 根据url 和可选参数拼接请求URL
	 * @param url
	 * @param params
	 * @return
	 */
	private static String getUrl(String url, Map<String, String> params) {
		StringBuilder sb = new StringBuilder(url);
		if(null != params){
			sb.append(url.indexOf("?")==-1?"?":"&");
			Set<String> keySet = params.keySet();
			for(String key : keySet){
				sb.append(key).append("=").append(params.get(key)).append("&");
			}
		}
		return sb.toString();
	}
	
	/**
	 * 执行http请求
	 * @param response
	 * @param method
	 * @return
	 * @throws HttpException
	 * @throws IOException
	 */
	private static String excuteMethod(String response, HttpMethod method) throws HttpException, IOException {
		int status = client.executeMethod(method);
		if(status == HttpStatus.SC_OK){
			response = method.getResponseBodyAsString();
		}else{
			logger.error("响应状态码 = " + method.getStatusCode());  
		}
		return response;
	}
	
}
